package com.tianqu.tms.www.api.network;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.fasterxml.jackson.databind.ObjectMapper;

public class PSHTTPUtil {
	public static String encryptDES(String encryptString, String key, String iv) throws Exception {
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
		SecretKeySpec skey = new SecretKeySpec(key.getBytes("UTF-8"), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.ENCRYPT_MODE, skey, zeroIv);
		byte[] encryptedData = cipher.doFinal(encryptString.getBytes("UTF-8"));
		return new String(Base64.encodeBase64(encryptedData));
	}

	public static String decryptDES(String decryptString, String key, String iv) throws Exception {
		byte[] byteMi = Base64.decodeBase64(decryptString.getBytes("GBK"));
		IvParameterSpec zeroIv = new IvParameterSpec(iv.getBytes());
		SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "DES");
		Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
		cipher.init(Cipher.DECRYPT_MODE, skey, zeroIv);
		byte decryptedData[] = cipher.doFinal(byteMi);
		return new String(decryptedData);
	}
	
	public static String convertJavaBeanToJson(Object bean)  throws Exception {
		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(bean);
		return json;
	}
	
	public static <T> T convertJsonToJavaBean(String json, Class<T> clazz)  throws Exception{
		ObjectMapper mapper = new ObjectMapper();
		return mapper.readValue(json, clazz);
	}
	
	public static <T> T convertObjectToJavaBean(Object json, Class<T> clazz) {
		ObjectMapper mapper = new ObjectMapper();
		return  mapper.convertValue(json, clazz);
	}
}
